﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;
using Microsoft.Practices.Unity;

using Might.Core.DOM;
using Might.Infrastructure.DOM;
using Might.Infrastructure.Events;
using Might.Infrastructure.Services;

namespace Might.Core.Services {

    public class LocalFileSystemService : IFileSystemService {
    
        private readonly IUnityContainer container;
        private IProgressToken progressToken;

        public LocalFileSystemService() {
            this.container = CoreServices.Container;
            CoreServices.EventAggregator.GetEvent<OpenFileSystemRootEvent>().Subscribe(OpenFileSystemRootEventHandler, ThreadOption.UIThread, false);
        }

        ///<summary>
        /// odchytava udalosti typu OpenFileSystemRoot a testuje datovy naklad
        ///zda je typu ISVN
        ///pokud je otevere jej
        ///odesila udalosti o Progressu
        ///po skonceni odesle udalost OpenFileSystemRootFinished< IEventResult >
        ///ten kdo tohle odchtyva si data pretypu na napr. EventFileSystemRootResult
        ///</summary>
        ///<param name="fs"></param>
        public void OpenFileSystemRootEventHandler( IFileSystemRoot fs ) {         

            if( !( fs is LocalFileSystemRoot ) ) return;
            
            LocalFileSystemRoot localFs = fs as LocalFileSystemRoot;
            progressToken = container.Resolve<IProgressService>().ProgressCreate( typeof( OpenFileSystemRootEvent ) , localFs );

            progressToken.Progress( 50 , "Opening file..." );

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Modelica source files (*.mo)|*.mo";

            if( dlg.ShowDialog().Value ) {
                
                Stream s = dlg.File.OpenRead();
                byte[] ar = new byte[s.Length];
                s.Read( ar , 0 , (int)s.Length );
                
                LocalFile file = new LocalFile();
                file.Data = new MemoryStream( ar );
                file.FileSystem = fs;
                file.Parent = fs;
                file.Uri = "";
                file.Name = dlg.File.Name;
                
                fs.InsertChild( GroupNames.File , file );

                progressToken.ProgressEnd( ProgressResult.Success , "File loaded." );
            
            } else {
                progressToken.ProgressEnd( ProgressResult.Fail , "File not loaded." );
            }
            
        }
     
    }
    
}
